/* This DOS utility converts a binary file into DW statements for use in *
 * assemblers such as AVOCET's AVMACZ80. DW statements save a little in  *
 * space over DB statements, but may be less readable.                   *
 *				written by Paul Hutchinson								  */


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "dos.h"


FILE	*infile, *outfile;  /* input & output files */


void DB(void)
{
	unsigned char lobyte,hibyte,loop=0,done=0;
	unsigned char line[]={"                "};
	int filebyte;
	long location = 0;

	while(!done)
		{
			if ((filebyte=getc(infile)) != EOF)
			{
				lobyte=filebyte & 255;
				if ((filebyte=getc(infile)) != EOF)
				{
					hibyte=filebyte & 255;
					if (loop==0)
					{
						if (hibyte < 16)
							fprintf(outfile,"\tdw\t00%x",hibyte);
						else
							fprintf(outfile,"\tdw\t0%x",hibyte);
					}
					else
					{
						if (hibyte < 16)
							fprintf(outfile,",00%x",hibyte);
						else
							fprintf(outfile,",0%x",hibyte);
					}
					if (lobyte < 16)
						fprintf(outfile,"0%xh",lobyte);
					else
						fprintf(outfile,"%xh",lobyte);
					if ((lobyte < 32) || (lobyte > 127))
						lobyte=32;
					line[loop++]=lobyte;
					if ((hibyte < 32) || (hibyte > 127))
						hibyte=32;
					line[loop++]=hibyte;
					if	(loop > 15)
					{
						fprintf(outfile,"\t;%5lx %s\n",location++ * 16,line);
						loop=0;
					}
				}
				else
				{
			   		if (lobyte < 16)
						fprintf(outfile,"\n\tdb\t0%xh",lobyte);
					else
						fprintf(outfile,"\n\tdb\t%xh",lobyte);
					done=1;
				}
			}
			else
				done=1;

		}
}

int main(int argc, char *argv[])
{
	if (argc != 3)
	{
		printf("DB: convert file\n");
		printf("Usage: DB infile outfile\n");
		return EXIT_FAILURE;
	}
	if ((infile = fopen(argv[1], "rb")) == NULL)
	{
		fprintf(stderr, "DB: Unable to open file: %s\n", argv[1]);
		return EXIT_FAILURE;
	}

	if ((outfile = fopen(argv[2], "w")) == NULL)
	{
		fprintf(stderr, "DB: Unable to create file: %s\n", argv[2]);
		return EXIT_FAILURE;
	}

	DB();

	fclose(infile);
	fclose(outfile);

	return EXIT_SUCCESS;
}




